/**
 * 访问明细
 *
 * @format
 */

import { initBaseDao } from '../sdk'
import { getToday } from '../utils'
import { ACCESS_DB_NAME } from '../db'

export default class UserAccessService {
  context: IContext<IParams>
  accessdao: IBaseDao
  constructor(context: IContext<IParams>) {
    this.context = context
    this.accessdao = initBaseDao(context, ACCESS_DB_NAME)
  }
  /**
   * 增加访问记录
   * @param {是否关注店铺} isFollow
   */
  async addAccess(userInfo: IUserInfo) {
    let { openId, data } = this.context
    let { pageId, userNick, avatar, inviteId, isVip = false } = data
    // 通过邀请链接访问的信息
    const inviteInfo = await this.accessdao.findOne({ pageId, openId, isReceiveShare: true })

    const today = getToday()
    await this.accessdao.insertOne({
      openId,
      pageId,
      userNick,
      avatar,
      isReceiveShare: !!inviteId,
      isFirstReceiveShare: !!inviteId && !inviteInfo,
      isVip,
      follow: userInfo.follow,
      member: userInfo.member,
      accessTime: Date.now(),
      createTime: Date.now(),
      updateTime: Date.now(),
      createDay: today
    })
    const firstLoginToday = userInfo?.login?.[today] === 1

    return { openId, firstLoginToday, newUser: userInfo.createDay === today && firstLoginToday }
  }
}
